package com.acme.service.bank.impl;

import com.acme.domain.account.Account;
import com.acme.domain.account.CheckingAccount;
import com.acme.domain.account.SavingAccount;
import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
import com.acme.exceptions.BrokenBankFeedFileException;
import com.acme.service.bank.BankCannotBeLoadedException;
import com.acme.service.bank.BankLoader;

import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BankLoaderFromFeedFile implements BankLoader {
    private final String path;

    public BankLoaderFromFeedFile(String path) {
        this.path = path;
    }

    /**
     * Loads a file which contains data feed in the following format: <br>
     * accounttype=c|s;balance=100;overdraft=50;name=John;gender=m|f;
     *
     * @return bank
     * @throws com.acme.service.bank.BankCannotBeLoadedException
     *          if file for specified path is not found or bank feed file contains broken data
     */
    @Override
    public Bank load() throws BankCannotBeLoadedException {
        Bank bank;
        try {
            Scanner scanner = new Scanner(new FileInputStream(path));
            BankFeedDataReader bankFeedDataReader = new BankFeedDataReader();
            bank = new Bank();
            while (scanner.hasNext()) {
                Client client = bankFeedDataReader.readClientLine(scanner.next());
                bank.addClient(client);
            }
        } catch (Exception e) {
            throw new BankCannotBeLoadedException(e);
        }
        return bank;
    }
}
